<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选择数字并提交</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 50px;
        }

        .dropdown-group {
            display: flex;
            flex-direction: row; /* 水平排列 */
            align-items: center;
            margin-bottom: 10px;
        }

        .dropdown-group label {
            margin-right: 10px;
        }

        select, button {
            margin: 5px;
            padding: 5px;
            width: 50%;
            max-width: 130px; /* 确保在小屏幕上也能正常显示 */
        }

        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .button-container {
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
            margin-bottom: 10px;
        }

        .container {
            border-bottom: 2px solid #ccc; /* 添加底部边框 */
            padding-bottom: 10px; /* 添加底部内边距 */
            margin-bottom: 10px; /* 添加底部外边距 */
        }

        .container {
            padding-top: 10px; /* 添加顶部内边距 */
        }

        input[type="text"] {
            border: 2px solid #ccc; /* 边框颜色 */
            border-radius: 5px; /* 圆角 */
            padding: 10px; /* 内边距 */
            font-size: 16px; /* 字体大小 */
            width: 80%; /* 宽度 */
            max-width: 300px; /* 最大宽度 */
            margin-bottom: 10px; /* 底部外边距 */
            transition: border-color 0.3s; /* 过渡效果 */
        }

        input[type="text"]:focus {
            border-color: #007BFF; /* 聚焦时的边框颜色 */
            outline: none; /* 去掉默认的聚焦轮廓 */
        }

        .dropdown-group-clss {
            flex-direction: column;
            align-items: stretch;
            gap: 8px;
        }

        .dropdown-group-clss select {
            width: 100%;
        }


        @media (max-width: 600px) {
            body {
                margin: 20px;
            }

            .dropdown-group {
                flex-direction: row; /* 垂直排列 */
                align-items: flex-start;
            }

            .dropdown-group label {
                margin-right: 0;
                margin-bottom: 5px;
            }

            select button {
                width: 50%;
                max-width: 80%;
            }

            .dx .ds .zh {
                width: 100% !important;
            }

            .dropdown-group-clss {
                flex-direction: column;
                align-items: stretch;
                gap: 8px;
            }

            .dropdown-group-clss select {
                width: 100%;
            }
        }

        /* 隐藏的textarea用于复制 */
        #clipboardTextarea {
            position: absolute;
            top: -9999px;
            left: -9999px;
        }


    </style>
</head>

<body>
<div class="container">
    <form id="numberForm">
        <div class="dropdown-group">
            <select id="dropdown1" name="dropdown1" class="num10">
                <!-- 使用JavaScript生成1到10的选项 -->
            </select>

            <select id="dropdown2" name="dropdown2" class="num10">
                <!-- 使用JavaScript生成1到10的选项 -->
            </select>
        </div>

        <div class="dropdown-group">
            <select id="dropdown3" name="dropdown3" class="num10">
                <!-- 使用JavaScript生成1到10的选项 -->
            </select>

            <select id="dropdown4" name="dropdown4" class="num10">
                <!-- 使用JavaScript生成1到10的选项 -->
            </select>
        </div>

        <button vitype="submit">提交</button>
    </form>
</div>

<div class="container">
    <div class="button-container">
        <input type="text" name="num" autocomplete="off"/>
    </div>
    <div class="button-container">
        <button onclick="generateCombinations4_1()">排除前4递增</button>
        <button onclick="generateCombinations4_2()">排除前4递减</button>
    </div>
    <div class="button-container">
        <button onclick="generateCombinations5_1()">排除前5递增&递减</button>
    </div>
</div>

<div class="container">
    <div class="button-container">
        <div class="dropdown-group">
            <div class="dropdown-group-clss">
                <select id="dropdown5" name="dropdown5" class="num10">
                </select>

                <select id="dropdown6" name="dropdown6" class="num10">
                </select>
            </div>
        </div>
    </div>
<!--    <div class="button-container">-->
<!--        <div class="dropdown-group">-->
<!--            <select id="dropdown7" name="" class="dx">-->
<!--            </select>-->

<!--            <select id="dropdown8" name="" class="ds">-->
<!--            </select>-->

<!--            <select id="dropdown9" name="" class="zh">-->
<!--            </select>-->
<!--        </div>-->
<!--    </div>-->
    <div class="button-container">
        <div class="button-container">
            <input type="text" name="num2" autocomplete="off"/>
        </div>
    </div>
    <div class="button-container">
        <button onclick="generateCombinations5_2()">生成</button>
    </div>
    <div class="button-container">
        <button onclick="generateCombinations5_3()">校验</button>
    </div>
</div>


<!-- 隐藏的textarea用于复制 -->
<textarea id="clipboardTextarea"></textarea>

<script>
    // 生成1到10的选项
    function populateDropdowns() {
        const dropdowns = document.querySelectorAll('.num10');
        dropdowns.forEach(dropdown => {
            for (let i = 1; i <= 10; i++) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = i;
                dropdown.appendChild(option);
            }
        });
        const dx = [
            {value: '', text: ''},
            {value: '1', text: '大'},
            {value: '2', text: '小'}
        ];
        const ds = [
            {value: '', text: ''},
            {value: '1', text: '单'},
            {value: '2', text: '双'}
        ];
        const zh = [
            {value: '', text: ''},
            {value: '1', text: '质'},
            {value: '2', text: '合'}
        ];
        populateDropdowns2('dx', dx)
        populateDropdowns2('ds', ds)
        populateDropdowns2('zh', zh)
    }

    function populateDropdowns2(dropdowns, optionsData) {
        const dropdowns1 = document.querySelectorAll('.' + dropdowns);
        dropdowns1.forEach(dropdown => {
            // 类型检查：确保是 select 元素
            if (!(dropdown instanceof HTMLSelectElement)) {
                console.warn('非 <select> 元素，跳过:', dropdown);
                return;
            }

            // 清空已有选项，防止重复添加
            dropdown.innerHTML = '';

            optionsData.forEach(data => {
                const option = document.createElement('option');
                option.value = data.value;
                option.textContent = data.text;
                dropdown.appendChild(option);
            });
        });
    }

    // 页面加载完成后填充下拉框
    window.onload = populateDropdowns;

    // 表单提交事件处理
    document.getElementById('numberForm').addEventListener('submit', function (event) {
        event.preventDefault(); // 阻止表单默认提交行为
        const firstNumber = document.getElementById('dropdown1').value;
        const secondNumber = document.getElementById('dropdown2').value;
        const thirdNumber = document.getElementById('dropdown3').value;
        const fourthNumber = document.getElementById('dropdown4').value;

        // 将选择的数字转换为数组
        const numbers1 = `${firstNumber.toString().padStart(2, '0')}${secondNumber.toString().padStart(2, '0')}`;
        const numbers2 = `${thirdNumber.toString().padStart(2, '0')}${fourthNumber.toString().padStart(2, '0')}`;

        // 生成两位数的组合并排除
        const twoDigitCombinations = new Set();
        for (let tens = 1; tens <= 10; tens++) {
            for (let units = 1; units <= 10; units++) {
                if (tens !== units) {
                    const twoDigitNumber = `${tens.toString().padStart(2, '0')}${units.toString().padStart(2, '0')}`;
                    twoDigitCombinations.add(twoDigitNumber);
                }
            }
        }

        // 从twoDigitCombinations中移除numbers1和numbers2
        twoDigitCombinations.delete(numbers1);
        twoDigitCombinations.delete(numbers2);

        // 将Set转换为数组以便使用join方法
        const twoDigitArray = Array.from(twoDigitCombinations);

        // 将过滤后的数字复制到剪贴板
        const filteredNumbers = twoDigitArray.join(';');

        // 使用隐藏的textarea进行复制
        const textarea = document.getElementById('clipboardTextarea');
        textarea.value = filteredNumbers;
        textarea.select();
        document.execCommand('copy');

        msg("已复制")
    });

    function msg(text) {
        // 使用消息框提醒
        const messageBox = document.createElement('div');
        messageBox.style.position = 'fixed';
        messageBox.style.top = '30%';
        messageBox.style.left = '50%';
        messageBox.style.transform = 'translate(-50%, -50%)';
        messageBox.style.backgroundColor = '#4CAF50';
        messageBox.style.color = 'white';
        messageBox.style.padding = '10px 20px';
        messageBox.style.borderRadius = '5px';
        messageBox.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
        messageBox.textContent = text;

        document.body.appendChild(messageBox);

        // 自动移除消息框
        setTimeout(() => {
            document.body.removeChild(messageBox);
        }, 3000);
    }

    function generateCombinations4_1() {
        const combinations = [];
        const combinations2 = [];

        // 生成除小到大外的组合
        for (let i = 1; i <= 10; i++) {
            for (let j = 1; j <= 10; j++) {
                for (let k = 1; k <= 10; k++) {
                    for (let l = 1; l <= 10; l++) {
                        if (i !== j && i !== k && i !== l && j !== k && j !== l && k !== l) {
                            const combination = [i, j, k, l];
                            const formattedCombination = combination.map(num => num.toString().padStart(2, '0')).join('');
                            // 检查是否严格递增
                            if (!(i < j && j < k && k < l)) {
                                // 格式化为两位数
                                combinations.push(formattedCombination);
                            } else {
                                combinations2.push(formattedCombination);
                            }
                        }
                    }
                }
            }
        }

        // 获取输入框中的数字
        const inputElement = document.querySelector('input[type="text"]');
        const numberOfCombinationsToRemove = parseInt(inputElement.value, 10);

        // 验证输入是否为有效的数字
        if (!isNaN(numberOfCombinationsToRemove) && numberOfCombinationsToRemove > 0) {
            // 随机移除指定数量的组合
            for (let i = 0; i < numberOfCombinationsToRemove && combinations2.length > 0; i++) {
                const randomIndex = Math.floor(Math.random() * combinations2.length);
                combinations2.splice(randomIndex, 1);
            }
        } else {
            // 如果未输入或输入无效，则移除所有组合
            combinations2.length = 0;
        }

        combinations.push(...combinations2)

        // 合并成字符串，数字间用;间隔
        const combinedString = combinations.join(';');

        // 使用隐藏的textarea进行复制
        const textarea = document.getElementById('clipboardTextarea');
        textarea.value = combinedString;
        textarea.select();
        document.execCommand('copy');

        // 计算组合数量
        const combinationCount = combinations.length;
        msg(`已复制 ${combinationCount} 种组合`);
    }

    function generateCombinations4_2() {
        const combinations = [];
        const combinations2 = [];

        // 生成所有可能的组合
        for (let i = 1; i <= 10; i++) {
            for (let j = 1; j <= 10; j++) {
                for (let k = 1; k <= 10; k++) {
                    for (let l = 1; l <= 10; l++) {
                        if (i !== j && i !== k && i !== l && j !== k && j !== l && k !== l) {
                            const combination = [i, j, k, l];

                            // 格式化为两位数
                            const formattedCombination = combination.map(num => num.toString().padStart(2, '0')).join('');
                            // 检查是否严格从大到小排列
                            if (!(i > j && j > k && k > l)) {
                                combinations.push(formattedCombination);
                            } else {
                                combinations2.push(formattedCombination);
                            }
                        }
                    }
                }
            }
        }

        // 获取输入框中的数字
        const inputElement = document.querySelector('input[type="text"]');
        const numberOfCombinationsToRemove = parseInt(inputElement.value, 10);

        // 验证输入是否为有效的数字
        if (!isNaN(numberOfCombinationsToRemove) && numberOfCombinationsToRemove > 0) {
            // 随机移除指定数量的组合
            for (let i = 0; i < numberOfCombinationsToRemove && combinations2.length > 0; i++) {
                const randomIndex = Math.floor(Math.random() * combinations2.length);
                combinations2.splice(randomIndex, 1);
            }
        } else {
            // 如果未输入或输入无效，则移除所有组合
            combinations2.length = 0;
        }

        combinations.push(...combinations2)

        // 合并成字符串，数字间用;间隔
        const combinedString = combinations.join(';');

        // 使用隐藏的textarea进行复制
        const textarea = document.getElementById('clipboardTextarea');
        textarea.value = combinedString;
        textarea.select();
        document.execCommand('copy');

        // 计算组合数量
        const combinationCount = combinations.length;
        msg(`已复制 ${combinationCount} 种组合`);
    }


    function generateCombinations5_1() {
        const combinations = [];
        const combinations2 = [];

        // 生成所有可能的五位数组合
        for (let i = 1; i <= 10; i++) {
            for (let j = 1; j <= 10; j++) {
                for (let k = 1; k <= 10; k++) {
                    for (let l = 1; l <= 10; l++) {
                        for (let m = 1; m <= 10; m++) {
                            if (i !== j && i !== k && i !== l && i !== m &&
                                j !== k && j !== l && j !== m &&
                                k !== l && k !== m &&
                                l !== m) {
                                const combination = [i, j, k, l, m];

                                // 格式化为两位数
                                const formattedCombination = combination.map(num => num.toString().padStart(2, '0')).join('');
                                // 检查是否严格递增&递减
                                if (!(i < j && j < k && k < l && l < m) && !(i > j && j > k && k > l && l > m)) {
                                    combinations.push(formattedCombination);
                                } else {
                                    combinations2.push(formattedCombination)
                                }
                            }
                        }
                    }
                }
            }
        }

        // 获取输入框中的数字
        const inputElement = document.querySelector('input[type="text"]');
        const numberOfCombinationsToRemove = parseInt(inputElement.value, 10);

        // 验证输入是否为有效的数字
        if (!isNaN(numberOfCombinationsToRemove) && numberOfCombinationsToRemove > 0) {
            // 随机移除指定数量的组合
            for (let i = 0; i < numberOfCombinationsToRemove && combinations2.length > 0; i++) {
                const randomIndex = Math.floor(Math.random() * combinations2.length);
                combinations2.splice(randomIndex, 1);
            }
        } else {
            // 如果未输入或输入无效，则移除所有组合
            combinations2.length = 0;
        }

        combinations.push(...combinations2)

        // 合并成字符串，数字间用;间隔
        const combinedString = combinations.join(';');

        // ✅ 使用兼容性更强的复制方法
        copyToClipboard(combinedString);
    }

    function generateAllUnique5DigitCombinations() {
        const combinations = [];
        for (let i = 1; i <= 10; i++) {
            for (let j = 1; j <= 10; j++) {
                for (let k = 1; k <= 10; k++) {
                    for (let l = 1; l <= 10; l++) {
                        for (let m = 1; m <= 10; m++) {
                            if (
                                i !== j && i !== k && i !== l && i !== m &&
                                j !== k && j !== l && j !== m &&
                                k !== l && k !== m &&
                                l !== m
                            ) {
                                const combination = [i, j, k, l, m];
                                const formattedCombination = combination.map(num => num.toString().padStart(2, '0'));
                                combinations.push(formattedCombination);
                            }
                        }
                    }
                }
            }
        }
        return combinations;
    }


    function generateCombinations5_2() {
        const combinations = generateAllUnique5DigitCombinations();
        // 在生成组合后调用洗牌函数
        shuffleArray(combinations);
        // 获取 dropdown5 和 dropdown6 的值
        const dropdown5 = parseInt(document.getElementById('dropdown5').value, 10);
        let dropdown6 = parseInt(document.getElementById('dropdown6').value, 10);
        dropdown6 = dropdown6.toString().padStart(2, '0')
        console.log("dropdown6:", dropdown6);
        let num = 505;

        // 映射 dropdown5 到对应的两位位置
        const toRemove = [];

        // 收集需要删除的元素
        for (let i = 0; i < combinations.length && num > 0; i++) {
            // for (let i = 0; i < 3; i++) {
            const comb = combinations[i];
            const digit1 = comb[dropdown5 - 1];
            if (digit1 === dropdown6) {
                toRemove.push(i);
                num--;
            }
        }
        // 从后往前删除（避免索引错乱）
        for (let i = toRemove.length - 1; i >= 0; i--) {
            combinations.splice(toRemove[i], 1);
        }

        // 4. 格式化为字符串
        const combinedString = combinations.map(item => item.join('')).join(';');
        // ✅ 使用兼容性更强的复制方法
        copyToClipboard(combinedString);
    }


    function copyToClipboard(text) {
        const textarea = document.getElementById('clipboardTextarea');
        textarea.value = text;
        // 优先尝试现代 API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text)
                .then(() => {
                    console.log("✅ 成功复制");
                    msg(`已复制 ${text.split(";").length} 种组合`);
                })
                .catch(err => {
                    console.warn("⚠️ 剪贴板API失败，尝试 execCommand", err);
                    fallbackCopyTextToClipboard(text);
                });
        } else {
            console.warn("⚠️ 浏览器不支持 clipboard API，使用 execCommand 回退");
            fallbackCopyTextToClipboard(text);
        }
    }

    // ✅ 回退方案：execCommand
    function fallbackCopyTextToClipboard(text) {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.top = "-9999px";
        textArea.style.left = "-9999px";
        textArea.style.position = "fixed";
        document.body.appendChild(textArea);

        try {
            textArea.focus();
            textArea.select();
            const successful = document.execCommand("copy");
            if (successful) {
                console.log("✅ execCommand 复制成功");
                msg(`已复制 ${text.split(";").length} 种组合`);
            } else {
                console.error("❌ execCommand 复制失败");
                msg("复制失败，请手动长按复制");
            }
        } catch (err) {
            console.error("❌ execCommand 抛出异常", err);
            msg("复制失败，请手动长按复制");
        } finally {
            document.body.removeChild(textArea);
        }
    }

    // 在生成组合之后、合并字符串之前添加以下代码
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1)); // 随机选择一个索引
            [array[i], array[j]] = [array[j], array[i]]; // 交换元素
        }
        return array;
    }

    function generateCombinations5_3() {
        // 获取输入框的值
        const input = document.querySelector('input[name="num2"]').value.trim();

        // 校验输入是否是5位数字
        if (!/^\d{5}$/.test(input)) {
            msg("请输入5位有效数字");
            return;
        }

        // 格式化每个数字为两位，其中 0 → 10，其他 → 两位补零
        const formattedDigits = input.split('').map(digit => {
            const num = parseInt(digit, 10);
            return num === 0 ? '10' : num.toString().padStart(2, '0');
        });

        // 拼接成10位字符串
        const targetCombination = formattedDigits.join('');
        console.log("目标组合:", targetCombination);

        // 获取剪贴板内容
        const clipboardContent = document.getElementById('clipboardTextarea').value;

        // 判断是否存在
        if (clipboardContent.includes(targetCombination)) {
            msg(`存在: ${targetCombination}`);
        } else {
            msg(`不存在: ${targetCombination}`);
        }
    }
</script>
</body>
</html>
